/**
 * Created with IntelliJ IDEA.
 * User: zzl
 * Date: 13-1-5
 * To change this template use File | Settings | File Templates.
 */
(function ($, undefined) {

    var $table;
    var editable;

    window.initTodoApi = function () {
        $table = $('#tblTodo');
        editable = $table.editable('get');

        $table.on('active', 'tr', function () {
            host.NotifyActiveTodoChanged();
        });
    };

    window.todo_cut = function () {

        var nodes = todolist.getSelectedSeparatedBranchNodes();
        clip.copy(nodes);
        todo_delete();

    };

    window.todo_copy = function () {
        var nodes = todolist.getSelectedSeparatedBranchNodes();
        clip.copy(nodes);
    };

    window.todo_hasSelection = function () {
        if(editable.isEditing()) {
            return editable.hasSelection();
        }
        else {
            var node = todolist.getActiveRow();
            if (!domex.inDomTree(node)) {
                return false;
            }
            return true;
        }
    };

    window.todo_getSelectedText = function() {
        if(!editable.isEditing()) {
            return '';
        }
        return editable.getSelectedText();
    };

    window.todo_delete = function () {

        editable.cancelIfEditing();

        var nodes = todolist.getSelectedSeparatedBranchNodes();
        var toActiveNode = todolist.getNodeToActiveAfterDeletion(nodes);

        var action = undoman.onAction({
            action: 'delete',
            nodes: nodes
        });

        todolist.deleteNode(nodes);
        todolist.notifyRowVisibilityChanged();
        if (toActiveNode) {
            todolist.setActiveRow(toActiveNode);
        }

        action.afterAction();
        //ttt
        $table.trigger('rowsChanged');

        gotFocus();
        host.NotifyChange();
    };

    window.todo_isSelected = function () {

    };

    window.todo_canUndo = function () {
        return undoman.canUndo();
    };

    window.todo_undo = function () {
        undoman.undo();
        host.NotifyChange();
    };

    window.todo_canRedo = function () {
        return undoman.canRedo();
    };

    window.todo_redo = function () {
        undoman.redo();
        host.NotifyChange();
    };

    window.todo_toggleActive = function () {
        var $node = $(todolist.getActiveRow());
        toggleNodeClass('active-todo', $table, $node);
        host.NotifyChange();
    };

    window.todo_toggleChecked = function () {
        todolist.toggleRowsChecked();
        host.NotifyChange();
    };

    window.todo_setPriority = function (priority) {
        var tr = todolist.getActiveRow();
        var $tr = $(tr);
        updateNodeData($table, $tr, 'priority', priority);
    };

    window.todo_toggleTag = function (tag) {
        toggleTag($table, tag);
    };

    window.todo_setColor = function (color) {
        var tr = todolist.getActiveRow();
        var $tr = $(tr);
        updateNodeData($table, $tr, 'color', color);
    };

    window.todo_toggleBold = function () {
        var tr = todolist.getActiveRow();
        var $tr = $(tr);
        toggleNodeClass('bold', $table, $tr);
    };

    window.todo_toggleItalic = function () {
        var tr = todolist.getActiveRow();
        var $tr = $(tr);
        toggleNodeClass('italic', $table, $tr);
    };

    window.todo_toggleUnderline = function () {
        var tr = todolist.getActiveRow();
        var $tr = $(tr);
        toggleNodeClass('underline', $table, $tr);
    };

    window.todo_isEditing = function () {
        return editable.isEditing();
    };

    window.todo_beginEdit = function () {
        var el = document.activeElement;
        if (!el || !$(el).is('.editable')) {
            var activeTr = todolist.getActiveRow();
            if (!domex.inDomTree(activeTr)) {
                return;
            }
            el = $(activeTr).find('.editable:first');
        }
        editable.edit($(el));
    };

    window.todo_endEdit = function () {
        editable.commit();
    };

    window.todo_add = function () {
        addTodo(host.isTopDownMode());
    };

    window.todo_addAfter = function () {
        addTodo(!host.isTopDownMode());
    };

    window.todo_addChild = function () {
        addTodo(host.isTopDownMode(), true);
    };

    window.todo_expandAll = function () {
        todolist.expandAll();
    };

    window.todo_collapseAll = function () {
        todolist.collapseAll();
    };

    window.todo_getSelectedTodos = function (todosResult) {
        var selectedNodes = todolist.getSelectedSeparatedBranchNodes();
        var todos = _getTodos($(selectedNodes));
        todosResult.Todos = todos;
    };

    window.todo_paste = function (todosHtml, pasteType) {
        var action = undoman.newAction({
            action: 'new'
        });

        var node = todolist.getActiveRow();

        var below = false, asChild = false;
        if(pasteType == 'before') {
            below = host.isTopDownMode();
        }
        else if(pasteType == 'after') {
            below = !host.isTopDownMode();
        }
        else if(pasteType == 'child') {
            asChild = true;
            below = host.isTopDownMode();
        }

        var pastedNodes = clip.pasteByRootNodesHtml(todosHtml, node, below, asChild);

        action.nodes = pastedNodes;
        undoman.onAction(action).afterAction();

        //ttt
        $table.trigger('rowsChanged');
        todolist.setActiveRow(pastedNodes[0], true);

        host.NotifyChange();
    };

    window.todo_pasteText = function(text) {
        editable.paste(text);
    };

    window.todo_setGridLineVisible = function (visible) {
        if (visible) {
            $table.removeClass('hideGridLine');
        }
        else {
            $table.addClass('hideGridLine');
        }
    };

    window.todo_setTreeLineVisible = function (visible) {
        if (visible) {
            $table.removeClass('hideTreeLine');
        }
        else {
            $table.addClass('hideTreeLine');
        }
    };

    window.todo_setHeaderVisible = function (visible) {
        $table.toggleClass('hideHeader', !visible).trigger('headerChange');
    };

    window.todo_setTheme = function(themeName) {
        setTheme(themeName);
    };

    window.todo_setReminder = function() {
        var node = todolist.getActiveRow();
        setupReminder($(node));
    };

    //
    window.todo_setNewIds = function(json) {
        var newIdMap = JSON.parse(json);
        todolist.setNewIds(newIdMap);
    };


    //
    window.todo_setActiveTodo = function(pathTitles) {
        pathTitles = pathTitles.split('\n');
        var node = todolist.findNodeByPathTitles(pathTitles);
        if(node) {
            todolist.ensureNodeExpanded(node);
            todolist.setActiveRow(node);
            flashTodo(node);
        }
        else {
            alert('"' + pathTitles.join('/') + '" not found');
        }
    };

    window.todo_getActiveTodo = function (todoResult) {
        var node = todolist.getActiveRow();
        if (!domex.inDomTree(node)) {
            todoResult.SetNull();
            return;
        }

        //
        var $node = $(node);
        var $tds = $node.children('td');
        var $td0 = $($tds[0]);
        var todo = interop.NewTodo();
        todo.Title = $td0.find('span.label').getEditText();
        todo.Progress = $($tds[1]).children().progressBar('value');
        todo.Due = $($tds[2]).getEditText();
        todo.Description = $($tds[3]).getEditText();
        todo.Checked = $td0.find(':checkbox').is(':checked') ? 1 : 0;
        todo.Active = $node.hasClass('active-todo') ? 1 : 0;

        var displayStyle = 'normal';
        if ($node.hasClass('italic')) {
            displayStyle += ',italic';
        }
        if ($node.hasClass('bold')) {
            displayStyle += ',bold';
        }
        if ($node.hasClass('underline')) {
            displayStyle += ',underline';
        }
        interop.SetTodoDisplayStyle(todo, displayStyle);

        var tags = $node.data('tags') || '';
        interop.SetTodoTags(todo, tags);

        todo.Color = $node.data('color') || '';
        todo.Priority = $node.data('priority') || 0;

        todoResult.todo = todo;
    }

})(jQuery);